<template>
  <div class="app-container">
    <div>
      区域选择：
      <el-tag
        v-for="(i, index) in areaOptions"
        style="margin: 0 30px"
        @click="handleQuery(i)"
        :key="index"
        >{{ i.areaName }}</el-tag
      >
    </div>
    <div v-if="hasChoose" style="margin-top: 20px">
      选中区域：
      <el-tag
        closable
        type="danger"
        style="margin: 0 30px"
        @close="resetQuery"
        >{{ areaName }}</el-tag
      >
    </div>
    <div style="margin-top: 20px">
      变电站名称：
      <el-tag
        type="info"
        v-for="(i, index) in substationDeviceList"
        :key="index"
        style="margin: 10px 30px"
        @click="toNew(i)"
        >{{ i.substationName }}</el-tag
      >
    </div>
  </div>
</template>

<script>
import {
  listSubstationDevice,
  getSubstationDevice,
  delSubstationDevice,
  addSubstationDevice,
  updateSubstationDevice,
  getProtectDeviceList,
} from "@/api/substation/substationDevice";
import { getProtectDevice } from "@/api/substation/protectDevice.js";
import { getVersionList } from "@/api/substation/version.js";
import {
  listParameterDetails,
  getHistory,
} from "@/api/substation/parameterDetails.js";
import { listSubstation } from "@/api/substation/substation.js";
import { listArea } from "@/api/substation/area.js";
import { getToken } from "@/utils/auth";

export default {
  name: "SubstationDevice",
  data() {
    return {
      value: "",
      areaName: "",
      hasChoose: false,
      id: "",
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 变电站设备信息表格数据
      substationDeviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        substationId: null,
        deviceNo: null,
        deviceName: null,
        switchNo: null,
        scheduleName: null,
        deviceVersion: null,
        checkCode: null,
        voltageLevel: null,
        ctTransformationRatio: null,
        ptTransformationRatio: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/substation/substationDevice/importData",
      },
      openDetail: false,
      version: false,
      radio: "1",
      openList: false,
      tableData: [],
      typeOptions: [],
      protectDeviceOptions: [],
      protectDeviceId: "",
      copyList: [],
      gridData: [],
      areaOptions: [],
      oldRouter: "",
    };
  },
  created() {
    this.getList();
    this.getAreaOptions();
    this.oldRouter = this.$route.path;
  },
  mounted() {
    this.$watch("$route.path", (newVal, oldVal) => {
      if (this.oldRouter == newVal) {
        this.getList();
        this.getAreaOptions();
      }
    });

    const unWatch = this.$watch("form.protectDeviceModel", (newVal, oldVal) => {
      // console.log(newVal,'newValue',newVal && !oldVal)
      if (newVal && !oldVal) {
        this.protectDeviceId = newVal;
        getProtectDevice(newVal).then((response) => {
          this.form = response.data;
        });
      } else {
        getVersionList({
          protectDeviceId: this.protectDeviceId,
          deviceId: this.id,
        }).then((response) => {
          this.copyList = response.data;
        });
      }
      // unWatch(); // 取消监听
    });
  },
  methods: {
    getAreaOptions() {
      this.loading = true;
      listArea(999).then((response) => {
        this.areaOptions = response.rows.map((item) => {
          return {
            id: item.id,
            areaName: item.areaName,
          };
        });
        this.loading = false;
        // console.log(this.areaOptions,'data')
      });
    },
    toNew(e) {
      // console.log(e.id,'e.id')
      this.$router.push("/substation/newDetails?id=" + e.id);
    },
    firstShow(e, a) {
      // console.log(e,'wwwwwwwwww',a)
      getHistory({
        deviceProtectVersionId: e.deviceProtectVersionId,
        serialNo: e.serialNo,
      }).then((response) => {
        this.gridData = response.data;
        // console.log(response,'data')
      });
    },
    // 查询所有变电站类型
    // getAlltype(){
    //   this.loading = true;
    //   getAllTypeList().then(response => {
    //     this.typeOptions = response.data
    //     this.loading = false;
    //   });
    // },
    // 选择版本
    chooseVersion(e) {
      listParameterDetails({
        deviceProtectVersionId: this.value,
      }).then((response) => {
        console.log(response.rows, "data");
        this.tableData = response.rows;
        this.openDetail = false;
        this.openList = true;
        this.title = "设备参数";
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 查询保护装置信息列表 */
    // getList() {
    //   this.loading = true;
    //   listProtectDevice(this.queryParams).then(response => {
    //     this.protectDeviceList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },

    /** 查询变电站设备信息列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams, "queryParams");
      listSubstation(this.queryParams).then((response) => {
        this.substationDeviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        substationId: null,
        deviceNo: null,
        deviceName: null,
        switchNo: null,
        scheduleName: null,
        deviceVersion: null,
        checkCode: null,
        voltageLevel: null,
        ctTransformationRatio: null,
        ptTransformationRatio: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(e) {
      this.hasChoose = true;
      this.queryParams.pageNum = 1;
      this.queryParams.areaId = e.id;
      this.areaName = e.areaName;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.areaId = "";
      this.hasChoose = false;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加变电站设备信息";
    },
    /** 参数详情操作 */
    detailList(row) {
      this.reset();
      const id = row.id || this.ids;
      this.id = id;
      this.loading = true;
      /** 查询变电站设备保护装置列表 */
      getProtectDeviceList({ id: id }).then((response) => {
        this.form = {};
        this.protectDeviceOptions = response.data.map((item) => {
          return {
            id: item.id,
            protectDeviceModel: item.protectDeviceModel,
          };
        });
        this.title = "设备参数列表";
        this.openDetail = true;
        this.loading = false;
      });

      // const id = row.id || this.ids
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.queryParams.pageSize = 999;
      this.loading = true;

      getSubstationDevice(id).then((response) => {
        this.form = response.data;
        console.log(this.form, "this.form");
        this.$nextTick(() => {
          this.open = true;
        });
        this.title = "修改变电站设备信息";
      });
      // listSubstation(this.queryParams).then(response => {
      //   // this.form.id = ''
      //   this.typeOptions = response.rows.map(item => {
      //     return {
      //       substationId:item.id,
      //       substationName:item.substationName
      //     }
      //   });
      //   this.loading = false;
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        console.log(this.form, "修改");
        if (valid) {
          if (this.form.id != null) {
            updateSubstationDevice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubstationDevice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除变电站设备信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSubstationDevice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "substation/substationDevice/export",
        {
          ...this.queryParams,
        },
        `substationDevice_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
